/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package executingimpl.buildservice;

import executing.IBuilder;
import executing.IProcessRunner;
import executingimpl.runner.BuildProcessRunner;
import executor.ExecutingException;
import executor.ExecutionItem;
import executor.ExecutionResult;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ryuju
 */
public class JavaBuilder implements IBuilder{
    
    @Override
    public boolean build(ExecutionItem execItem, String tempDir) throws ExecutingException{
        
        File srcFile = new File(tempDir, "Main.java");
        String cmd = srcFile.getAbsolutePath();
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            
            // create source file
            fw = new FileWriter(srcFile.getAbsoluteFile());
            bw = new BufferedWriter(fw);
            bw.write(execItem.srcCode);
            
            bw.close();
            fw.close();
 
            if (false == srcFile.exists()) {
                ExecutingException ee = new ExecutingException();
                ee.msg = "fail creating source file";
                throw ee;
            }
            
            // make build command
            List<String> cmdList = new ArrayList<>();
            cmdList.add("javac");
            cmdList.add(cmd);
            
            IProcessRunner runner = new BuildProcessRunner();
            ExecutionResult execResult = runner.run(cmdList);
            
            if(execResult.errOccured)
            {
                throw new ExecutingException(execResult.errMsg);
            }
            return true;
        } 
        catch(ExecutingException ee)
        {
            ee.msg = "[Build Fail]: " + ee.msg;
            throw ee;
        }
        catch(Exception e)
        {
            throw new ExecutingException("[Build Fail] :" + e.getMessage());
        }
    }
    
}
